//
//  RoomModel.m
//  SmartiOSPublisher
//
//  Created by Liu,Qingcan on 2017/4/25.
//  Copyright © 2017年 Baidu. All rights reserved.
//

#import "RoomModel.h"



@implementation RoomModel
- (void)insertRoomData:(LERoomItem *)item{
    PersistenceCommon *common = [PersistenceCommon shareInstance];
    //创建需要保存的对象personOne
    
    Room *One = [NSEntityDescription insertNewObjectForEntityForName:@"Room"inManagedObjectContext:common.currentContext];
    
    //设置personOne的属性，这里personOne和我们平常用的person实例有一点区别，它无法通过点语法直接拿到属性（后面有解决方法），只能通过KVC来设置它的属性
    
    One.nid = item.nid;
    One.title = item.title;
    One.classhour = item.classhour;
    NSString *fetures = [NSString stringWithFormat:@""];
    for(NSString *fe in item.feature){
        [fetures stringByAppendingString:fe];
        [fetures stringByAppendingString:@" "];
    }
    One.feature = fetures;
    One.validtime = item.validtime;
    One.image = item.image;
    One.category_id = item.category_id;
    One.price = item.price;
    
    // 利用上下文对象，将数据同步到持久化存储库
    NSError *errors = nil;
    //保存数据
    BOOL success =[common.currentContext save:&errors];
    
    if (!success) {
        [NSException raise:@"数据库访问错误" format:@"%@",[errors localizedDescription]];
    }
    

}


/**
 * number 是起始数字
 */
- (NSArray *)selectNumberOfData:(NSInteger)number cateId:(NSInteger)cateId{
    NSMutableArray *result = [NSMutableArray array];
    
//    PersistenceCommon *common = [PersistenceCommon shareInstance];
    //得到要查询的表
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Room" inManagedObjectContext:self.persistence.currentContext];
    //建立查询的工具类
    NSFetchRequest *req = [[NSFetchRequest alloc]init];
    [req setEntity:entity];
    //谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"category_id = %d",cateId];
    [req setPredicate:predicate];
    
    //结果
    NSError *error = nil;
    NSArray *objs = [self.persistence.currentContext executeFetchRequest:req error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    int endFlag = 0;
    int countNumber = objs.count-10;
    if ( countNumber>= number) {
        endFlag = 10;
    }else{
        if(objs.count >= number){
            endFlag = objs.count - number;
        }else{
            return result;
        }

    }

    // 遍历数据
    for (int index = 0; index < endFlag; index ++) {
        Room *item = objs[index+number];
        LERoomItem *One = [LERoomItem new];
        
        One.nid = item.nid;
        One.title = item.title;
        One.classhour = item.classhour;
        NSArray *features = [item.feature componentsSeparatedByString:@" "];
        One.feature = features;
        One.validtime = item.validtime;
        One.image = item.image;
        One.category_id = item.category_id;
        One.price = item.price;
        


        
        [result addObject:One];
    }
    
//    for (Room *obj in objs) {
//        
//        
//        NSLog(@"name=%@", [obj valueForKey:@"username"] ) ;
//        NSLog(@"pwd=%@", [obj valueForKey:@"userpwd"] ) ;
//    }
    
    
    
    return [result copy];
}



- (NSArray *)selectRoomsByCeteId:(NSInteger)cateId{
    //    NSMutableArray *result = [NSMutableArray array];
    
    //得到要查询的表
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Room" inManagedObjectContext:self.persistence.currentContext];
    //建立查询的工具类
    NSFetchRequest *req = [[NSFetchRequest alloc]init];
    [req setEntity:entity];
    //谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"category_id = %d",cateId];
    [req setPredicate:predicate];
    
    //结果
    NSError *error = nil;
    NSArray *array = [self.persistence.currentContext executeFetchRequest:req error:&error];
    
    
    
    return array;
}



- (LERoomItem *)selectRoomsByRoomId:(NSInteger)roomId{
//    NSMutableArray *result = [NSMutableArray array];
    
    //得到要查询的表
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Room" inManagedObjectContext:self.persistence.currentContext];
    //建立查询的工具类
    NSFetchRequest *req = [[NSFetchRequest alloc]init];
    [req setEntity:entity];
    //谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"nid = %d",roomId];
    [req setPredicate:predicate];
    
    //结果
    NSError *error = nil;
    NSArray *array = [self.persistence.currentContext executeFetchRequest:req error:&error];
   
    Room *item = array.firstObject;
    LERoomItem *One = [LERoomItem new];
    One.nid = item.nid;
    One.title = item.title;
    One.classhour = item.classhour;
    NSArray *features = [item.feature componentsSeparatedByString:@" "];
    One.feature = features;
    One.validtime = item.validtime;
    One.image = item.image;
    One.category_id = item.category_id;
    One.price = item.price;

//    [result addObject:One];

    
   
    
    
    
    return One;
    
    return array;
}



- (void)deleteRoom:(Room *)item{
    [self.persistence.currentContext deleteObject:item];
    // 将结果同步到数据库
    NSError *error = nil;
    [self.persistence.currentContext save:&error];
    if (error) {
        [NSException raise:@"删除错误" format:@"%@", [error localizedDescription]];
    }
}



- (void)updateRoom:(Room *)item{
    //得到要查询的表
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Room" inManagedObjectContext:self.persistence.currentContext];
    //建立查询的工具类
    NSFetchRequest *req = [[NSFetchRequest alloc]init];
    [req setEntity:entity];
    //谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"nid = %d",item.nid];
    [req setPredicate:predicate];
    
    //结果
    NSError *error = nil;
    NSArray *array = [self.persistence.currentContext executeFetchRequest:req error:&error];
    
    
    //遍历结果集更改对象属性
    for (Room *One in array) {
        One.nid = item.nid;
        One.title = item.title;
        One.classhour = item.classhour;
        One.feature = item.feature;
        One.validtime = item.validtime;
        One.image = item.image;
        One.category_id = item.category_id;
    }
    [self deleteRoom:array.firstObject];
    
    //更新操作需要同步
    // 利用上下文对象，将数据同步到持久化存储库
    NSError *errors = nil;
    //保存数据
    BOOL success =[self.persistence.currentContext save:&errors];
    if (!success) {
        [NSException raise:@"数据库访问错误" format:@"%@",[errors localizedDescription]];
    }

}



- (void)deleteAllRoom{
    NSMutableArray *result = [NSMutableArray array];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Room" inManagedObjectContext:self.persistence.currentContext];
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"nid" ascending:NO];
    request.sortDescriptors = [NSArray arrayWithObject:sort];
    // 执行请求
    NSError *error = nil;
    NSArray *objs = [self.persistence.currentContext executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
    
    // 遍历数据
    for (int index = 0; index < objs.count; index ++) {
        [result addObject:objs[index]];
    }
    for (Room *item in result) {
        [self.persistence.currentContext deleteObject:item];
    }
    
    // 将结果同步到数据库
    //    NSError *error = nil;
    [self.persistence.currentContext save:&error];
    if (error) {
        [NSException raise:@"删除错误" format:@"%@", [error localizedDescription]];
    }
    
}



- (PersistenceCommon *)persistence{
    if (!_persistence) {
        _persistence = [PersistenceCommon shareInstance];
    }
    return _persistence;
}


@end
